#!/bin/bash

. /etc/rc.common
TOP_URL="http://www.atvMod.com/repository/"
PROJECT_VERSION="1.0"
HASH="1605e79a4c2e7c92dc208c6855e1b343"
VAR_FILE="/Users/frontrow/atvMod_com/scripts/common.vars"

if [ -f /Users/frontrow/atvMod_com/.patched ]; then
  # Already Patched Don't do anything.
  exit 0;
fi

if [ -f /Users/frontrow/atvMod_com/scripts/init.sh ]; then 
  # Not yet Patched and init.sh exists. Run it.
  sudo /Users/frontrow/atvMod_com/scripts/init.sh
else
  # Not yet Patched and init.sh doesn't exists. First timer.
  sudo mount -uw /
  sudo mkdir -p /Users/frontrow/atvMod_com/{logs,packages,receipts,scripts}
  sudo chown -R frontrow:frontrow /Users/frontrow/atvMod_com/
  sudo chmod -R 755 /Users/frontrow/atvMod_com/

  # Install scripts
  cd /Users/frontrow/atvMod_com/packages

  GOT_NETWORK=NO
  while [ $GOT_NETWORK = NO ]; do
    wget -q $TOP_URL/$PROJECT_VERSION/$HASH/scripts.rar
    if [ -f scripts.rar ]; then
      GOT_NETWORK=YES
    fi
    sleep 5
  done
  unset GOT_NETWORK

  # Unpack and fix perms
  rar x scripts.rar
  cp /Users/frontrow/atvMod_com/packages/scripts/* /Users/frontrow/atvMod_com/scripts/
  sudo chown -R frontrow:frontrow /Users/frontrow/atvMod_com/scripts
  sudo chmod +x /Users/frontrow/atvMod_com/scripts/*

  # Set Variables
  echo " " >> $VAR_FILE
  echo "# Remote Information" >> $VAR_FILE
  echo "TOP_URL=\"$TOP_URL\"" >> $VAR_FILE
  echo "PROJECT_VERSION=\"$PROJECT_VERSION\"" >> $VAR_FILE
  echo "HASH=\"$HASH\"" >> $VAR_FILE

  # Run init.sh
  sudo /Users/frontrow/atvMod_com/scripts/init.sh

  # Clean up
  cd sudo /Users/frontrow/
  sudo rm -rf /Users/frontrow/atvMod_com/scripts/
fi
